package com.example.foo.admin.web.ftt;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtils;
import com.example.core.PageResult;
import com.example.core.Pageable;
import com.example.foo.ftt.model.FttProfit;
import com.example.foo.ftt.query.FttProfitQuery;
import com.example.foo.ftt.service.FttProfitFacadeService;
import com.example.foo.ftt.service.FttProfitService;

@org.springframework.web.bind.annotation.RestController
public class FttProfitAction {

	private final FttProfitService fttProfitService;
	private final FttProfitFacadeService fttProfitFacadeService;

	public FttProfitAction(FttProfitService fttProfitService,
			FttProfitFacadeService fttProfitFacadeService) {
		this.fttProfitService = fttProfitService;
		this.fttProfitFacadeService = fttProfitFacadeService;
	}

	@GetMapping("/api/fttprofits")
	public AjaxResult index(FttProfitQuery fttProfitQuery, Pageable pageable) {
		PageResult<FttProfit> pageResult = fttProfitService.findFttProfits(fttProfitQuery, pageable);
		List<FttProfitVO> fttProfitVOs = pageResult.getRows().stream()
				.map(FttProfitVO::new)
				.collect(Collectors.toList());
		return AjaxResult.successData(new PageResult<>(fttProfitVOs, pageResult.getTotal()));
	}

	@GetMapping("/api/fttprofits/export")
	public AjaxResult export(FttProfitQuery fttProfitQuery) {
		Pageable pageable = new Pageable(1, 65535);
		PageResult<FttProfit> pageResult = fttProfitService.findFttProfits(fttProfitQuery, pageable);

		List<FttProfitVO> fttProfitVOs = pageResult.getRows().stream()
				.map(FttProfitVO::new)
				.collect(Collectors.toList());

		Map<String, String> fields = new LinkedHashMap<>();
		fields.put("ID", "id");
		fields.put("网体级别", "fttLevel");
		fields.put("网体级别T", "fttLevelText");
		fields.put("总金额", "totalMoney");
		fields.put("账期日期", "periodDay");
		fields.put("状态", "state");
		fields.put("用户数", "userCount");
		fields.put("每用户分账金额", "perUserMoney");
		fields.put("总已分账金额", "settleMoney");
		return new ExcelUtils<>(FttProfitVO.class).export(fields, fttProfitVOs);
	}

	@PostMapping("/api/fttprofits/cashorder")
	public AjaxResult createFttProfit4CashOrder(@RequestParam("quantity") Integer quantity) {
		if (quantity == null) {
			return AjaxResult.error(400, "quantity must not be null");
		}
		if (quantity < 1) {
			return AjaxResult.error(400, "quantity must not be less than 1");
		}

		fttProfitFacadeService.updateFttProfitIncrement4CashOrder(quantity);

		return AjaxResult.success();
	}

}
